<template>
  <div v-if="!loading">
    <!-- 头部插槽 -->
    <slot :data="{ hastag: hastag, headinfo: headinfo, handleAddTag: handleAddTag, tags: tags }"></slot>

    <!--  -->
    <div style="margin:0px auto;margin-top: 20px;"></div>
    <van-notice-bar :mode="showNoticeWrapable ? '' : 'link'" v-if="notice"
      @click="showNoticeWrapable = !showNoticeWrapable" :wrapable="showNoticeWrapable" :scrollable="!showNoticeWrapable">

      <template #default>
        <div v-show="!showNoticeWrapable">{{ notice }}</div>
        <div v-show="showNoticeWrapable" v-for="(item, index) in noticeArr" :key="index" style="margin-bottom: 20px;">
          <i class="iconfont icon-radio"></i>{{ item }}
        </div>
      </template>
    </van-notice-bar>
    <!-- Tabs -->
    <CardTabs :mode="mode" :hasdynamic="hasdynamic" :activeTab="activeTab" :details-arr="detailsArr"
      :dynamic-arr="dynamicArr" :handle-click-operation="handleClickOperation" :operation="operation"
      :operation-more-actions="operationMoreActions" :handleChangeTab="handleChangeTab" :relevant="relevant"
      :handleRelAdd="handleRelAdd" :handleShowDetail="handleShowDetail" :scenario="scenario"
      :businessMenusArr="businessMenusArr" :getBusinessMenus="getBusinessMenus" :itemid="itemid" :idobject="idobject" />
    <div class="L-bottom-space"></div>
  </div>

  <!-- 标签弹窗 -->
  <van-popup v-model:show="showTagPopup" position="bottom" style="width: 100%;height:100%">
    <NewTag v-if="showTagPopup" @handleTagConfirm="handleTagConfirm" @handleTagCancle="handleTagCancle"></NewTag>
  </van-popup>

  <!-- 新增弹窗 -->
  <van-popup v-model:show="showNewPopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showNewPopup" :loadapi="relLoadApi" :loadParams="relLoadParams" :submitapi="relSubmitapi"
      :callBack="handleRelSubmit" mode="pop" :idobject="activeTab"></Form>
  </van-popup>

  <!-- 编辑弹窗 -->
  <van-popup v-model:show="showEditPopup" position="bottom" style="width: 100%;height:100%">

    <Form v-if="showEditPopup" :loadapi="editApi" :loadParams="editParams" :submitapi="editSubmitapi"
      :callBack="afterEditSubmit" mode="pop" :idobject="idobject" :itemid="itemid"></Form>
  </van-popup>

  <!-- 关闭弹窗 -->
  <van-popup v-model:show="showClosePopup" position="bottom" style="width: 100%;height:50%">
    <div style="position: relative;">
      <div style="text-align: center;margin:20px auto">关闭</div>

      <FormInput v-for="(item, index) in closeFieldArr" :key="index" :formItem="item" @handleChange="handleCloseChange">
      </FormInput>

      <van-sticky position="bottom">
        <div class="L-bottom-row">
          <div class="L-operate-btn" @click="showClosePopup = false">取消</div>
          <div class="L-operate-btn" @click="handleCloseSubmit()">保存</div>

        </div>
      </van-sticky>


    </div>
  </van-popup>


  <!-- 变更弹窗 -->
  <van-popup v-model:show="showChangePopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showChangePopup" :loadapi="changeApi" :loadParams="changeParams" :submitapi="chnageSubmitapi"
      :callBack="alterChangeSubmit" mode="pop" :idobject="idobject"></Form>
  </van-popup>

  <!-- 续签弹窗 -->
  <van-popup v-model:show="showRenewPopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showRenewPopup" :loadapi="renewApi" :loadParams="renewParams" :submitapi="renewSubmitapi"
      :callBack="alterRenewSubmit" mode="pop" :idobject="idobject"></Form>
  </van-popup>

  <!-- 详情弹窗 -->
  <van-popup v-model:show="showDetailPopup" position="bottom" style="width: 100%;height:90vh">
    <Card mode="pop" v-if="showDetailPopup" :itemid="detailId" :idobject="activeTab"></Card>
  </van-popup>

  <!-- 拜访记录弹窗 -->
  <van-popup v-model:show="showBfjlPopup" position="bottom" style="width: 100%;height:100vh">
    <Form v-if="showBfjlPopup" :loadapi="bfjlLoadApi" :loadParams="bfjlLoadParams" :submitapi="bfjlSubmitApi"
      :callBack="handleBfjlSubmit" mode="pop" :idobject="idobject"></Form>
  </van-popup>

  <!-- 认款弹窗 -->
  <van-popup v-model:show="showRkPopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showRkPopup" :loadapi="rkApi" :loadParams="rkParams" :submitapi="rkSubmitapi" :callBack="alterRkSubmit"
      mode="pop" idobject="skd"></Form>
  </van-popup>

  <!-- 评价弹窗 -->
  <van-popup v-model:show="showReviewPopup" closeable round position="bottom" style="width: 100%;height:220px">
    <div style="margin:10px auto;text-align: center;">点评</div>
    <van-field v-model="reviewContent" rows="5" type="textarea" maxlength="100" placeholder="请输入点评内容" show-word-limit />
    <!-- <div class="L-bottom-space"></div> -->

    <div class="L-bottom-row" style="border:none">
      <van-button round type="default" style="width:40%" @click="showReviewPopup = false">取消</van-button>
      <van-button round type="primary" style="width:40%" @click="handleReviewSubmit">保存</van-button>
    </div>


  </van-popup>

  <!--  会议预算报销  -->
  <van-popup v-model:show="showHyysbxPopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showHyysbxPopup" :loadapi="hyysbxApi" :loadParams="hyysbxParams" :submitapi="hyysbxSubmitapi"
      :callBack="afterHyysbxSubmit" mode="pop" idobject="feebill"></Form>
  </van-popup>

  <!--  会议讲者报销  -->
  <van-popup v-model:show="showHyjzbxPopup" position="bottom" style="width: 100%;height:100%">
    <Form v-if="showHyjzbxPopup" :loadapi="hyjzbxApi" :loadParams="hyjzbxParams" :submitapi="hyjzbxSubmitapi"
      :callBack="alterHyjzbxSubmit" mode="pop" idobject="feebill"></Form>
  </van-popup>



  <!-- 业务定制组件 -->

  <van-popup v-model:show="showBusinessCustomizationPopup" position="bottom" style="width: 100%;height:90%" round>
    <component :is="currentBusinessComponent" :businessName="currentBusinessName"
      :handleBusinesSubmit="handleBusinesSubmit" :handleBusinessCancle="handleBusinessCancle" :idobject="activeTab"
      :headObject="idobject" :headObjectId="itemid" />
  </van-popup>

  <!-- 纠错 -->
  <van-popup round v-model:show="showErrorCorrectionPopup" position="bottom" style="width: 100%;height:90vh">
    <ErrorCorrection mode="pop" v-if="showErrorCorrectionPopup" :idobject="idobject"
      :callBack="afterErrorCorrectionSubmit" :itemid="itemid">
    </ErrorCorrection>
  </van-popup>


  <div class="L-bottom-row" v-if="businessMenusArr.length > 0"
    :style="{ justifyContent: businessMenusArr.length == 1 ? 'center' : 'space-evenly' }">
    <template v-for="(item, index) in businessVisibleMenuButtons" :key="index">
      <div class="L-operate-btn" @click="handleClickBusinessButton(item)">{{ item.title }}</div>
    </template>

    <van-popover v-model:show="showMoreBusinessMenusPopover" placement="top-end" :actions="businessHiddenMenuActions"
      @select="handleClickBusinessButton">
      <template #reference>
        <div v-if="businessMenusArr.length > maxVisibleButtons" class="L-operate-more-btn">
          <i class="iconfont icon-icon_more L-title"></i>
        </div>
      </template>
    </van-popover>
  </div>










</template>


<script setup lang="ts">
import { reactive, onMounted, ref, defineAsyncComponent, computed, watch } from "vue";
import emitter from "@/utils/emitter";
// import Card from "@/components/common/Card.vue";
import CardTabs from "@/components/base/Card/CardTabs.vue";
import FormInput from "@/components/base/Form/FormInput.vue";
import ErrorCorrection from "@/components/base/ErrorCorrection/ErrorCorrection.vue";

import NewTag from "@/components/common/NewTag.vue";
import Form from "@/components/common/From.vue";

import { apiConfigurable } from "@/request/api/api";

import { closeToast, showLoadingToast, showConfirmDialog, showToast, showSuccessToast } from "vant";
import { useRoute, useRouter } from "vue-router";



const router = useRouter();
const route = useRoute();

import { useRouterStore } from "@/stores/router";
import ContactForm from "@/views/Modules/contact/contactForm.vue";
const routerStore = useRouterStore();

const headinfo = ref({});
const operation = ref([]);
const detailsArr = ref([]);
const tags = ref([]);

const relevant = ref([]);
const hasdynamic = ref(0);
const dynamicArr = ref([]);
const scenario = ref({});

const notice = ref("")
const noticeArr = ref([])
const showNoticeWrapable = ref(false)



const props = defineProps({
  mode: {
    type: String,
    default: "page",
  },
  idobject: {
    type: [String, Array],
    default: "",
  },
  itemid: {
    type: [String, Array],
    default: "",
  },
  idtemplate: {
    type: [String, Array],
    default: "",
  },
});

const activeTab = ref("");
const operationMoreActions = ref([]);
const maxVisibleButtons = 2


// 业务定制
const businessMenusArr = ref([])
const currentBusinessRel = ref(null)
const currentBusinessComponent = ref(null)
const currentBusinessObject = ref("")
const currentBusinessName = ref("")
const showMoreBusinessMenusPopover = ref(false)
const showBusinessCustomizationPopup = ref(false)

function getBusinessMenus(arr) {
  businessMenusArr.value = arr
}
function handleClickBusinessButton(item) {

  switch (item.text) {
    case "选择发票":

      currentBusinessComponent.value = defineAsyncComponent(async () => await import('@/components/base/BusinessCustomization/Upload.vue'));

      break;

    case "上传协议":
      currentBusinessComponent.value = defineAsyncComponent(async () => await import('@/components/base/BusinessCustomization/Upload.vue'));

      break;
  }


  currentBusinessName.value = item.text
  showBusinessCustomizationPopup.value = true



}

function handleBusinessCancle() {
  showBusinessCustomizationPopup.value = false
}
function handleBusinesSubmit() {
  showBusinessCustomizationPopup.value = false
  emitter.emit("listUpload");

}






//切换tab时清空业务按钮
watch(activeTab, (value) => {
  businessMenusArr.value = []
})

const businessVisibleMenuButtons = computed(() => {
  return businessMenusArr.value.slice(0, maxVisibleButtons).map(item => { return { ...item, text: item.title } }) || []
})

const businessHiddenMenuButtons = computed(() => {
  return (businessMenusArr.value.length > maxVisibleButtons && businessMenusArr.value.slice(maxVisibleButtons, businessMenusArr.value.length)) || []
})


const businessHiddenMenuActions = computed(() => {
  return businessHiddenMenuButtons.value.map(item => { return { text: item.title } })
})















onMounted(() => {
  getData();
});

interface params {
  [idx: string]: any;
}

const loading = ref(false);
function getData() {
  const { idobject, itemid, idtemplate } = props;
  const params: params = {};
  params[`${idobject}_id`] = itemid;
  params[`${idobject}_idtemplate`] = idtemplate;

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  loading.value = true;
  const url = `${idobject}.check.do`;

  apiConfigurable(url, params).then(async (res) => {
    const jsondata = res.data.jsondata;

    headinfo.value = jsondata.headinfo;
    operation.value = jsondata.operation || [];


    // 设置operation的判断(老版的判断,建议删除,通过配置实现)=======================================
    if (route.query.idobject == 'currentstock') {
      operation.value = []
    } else if (['dailyreports', 'weekreports', 'monthreport1', 'yzlh2', 'pxjlb', 'activity', 'campaign', 'activitycust', 'activitybiz'].indexOf(route.query.idobject as string) >= 0) {
      operation.value.push({ title: '点评', mobileFunc: 'review' })
    } else if (route.query.idobject === 'dailyreports') {
      operation.value.push({ title: '轨迹', mobileFunc: 'showPath' })
    }
    // =====================================================================================

    if (operation.value.length > 2) {
      operationMoreActions.value = operation.value
        .filter((item, index) => index > 1)
        .map((item) => {
          return { text: item.title, ...item };
        });
    }

    detailsArr.value = jsondata.Details.map((item) => {
      return { expand: true, ...item };
    });

    hastag.value = jsondata.hastag;
    tags.value = jsondata.tags;
    relevant.value = jsondata.relevant;

    hasdynamic.value = jsondata.hasdynamic;
    // 动态
    if (hasdynamic.value) {
      const dynamicRes = await getDynamic();
      activeTab.value = "dynamics";
      if (dynamicRes.code === 0) {
        dynamicArr.value = dynamicRes.data.jsondata;
      }
    }
    // 场景
    if (jsondata.scenario) {
      activeTab.value = "scenario";
      scenario.value = jsondata.scenario;
    }

    //通知

    if (jsondata.confirmmsg?.contents?.length > 0) {
      notice.value = jsondata.confirmmsg?.contents?.reduce((pre, item, index) => {
        return `${pre}${item} `
      }, "")

      noticeArr.value = jsondata.confirmmsg?.contents?.map((item) => {
        return item
      })

    }



    loading.value = false;

    closeToast();
  });
}

function getDynamic() {
  const { idobject, itemid, idtemplate } = props;

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  const params = {
    page: 0,
    start: 0,
    bo: idobject,
    id: itemid,
  };
  const url = "dynamic.list.do";
  return apiConfigurable(url, params);

  // apiConfigurable(url, params).then((res) => {
  //   dynamicArr.value = res.data.jsondata;
  //   closeToast();
  // });
}

function handleChangeTab(value) {
  activeTab.value = value;
}

// 标签相关=================================
const hastag = ref(0);
const showTagPopup = ref(false);

function handleAddTag() {
  showTagPopup.value = true;
}

function handleTagCancle() {
  showTagPopup.value = false;
}

function handleTagConfirm() {
  showTagPopup.value = false;
  getData();
}

//新增相关=================================
interface relitem {
  cannew: string;

  current_object: string;

  current_toobject: string;

  current_toobjectid: string;

  display: string;

  relfield: string;

  relvalue: string;

  title: string;

  ui_key: string;

  view_id: string;
}

const showNewPopup = ref(false);
const relLoadApi = ref("");
const relSubmitapi = ref("");
const relLoadParams = reactive<params>({});

function handleRelAdd(relitem: relitem) {
  showNewPopup.value = true;
  const { itemid } = props;

  relLoadApi.value = relitem.current_object + ".new.do";
  relSubmitapi.value = relitem.current_object + ".newsave.do";
  relLoadParams[`${relitem.current_object}_${relitem.relfield}`] = itemid;
}

function handleRelSubmit() {

  showNewPopup.value = false;
  emitter.emit("listUpload");
}

//详情 =====================================
const showDetailPopup = ref(false);
const detailId = ref("");
function handleShowDetail(itemid) {
  showDetailPopup.value = true;
  detailId.value = itemid;
}

function updateDetail() {
  const { idobject, itemid, idtemplate } = props;
  const params: params = {};
  params[`${idobject}_id`] = itemid;
  params[`${idobject}_idtemplate`] = idtemplate;

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  const url = `${idobject}.check.do`;

  apiConfigurable(url, params).then(async (res) => {
    const jsondata = res.data.jsondata;

    headinfo.value = jsondata.headinfo;
    operation.value = jsondata.operation || [];

    if (operation.value.length > 2) {
      operationMoreActions.value = operation.value
        .filter((item, index) => index > 1)
        .map((item) => {
          return { text: item.title, ...item };
        });
    }

    detailsArr.value = jsondata.Details.map((item) => {
      return { expand: true, ...item };
    });
    closeToast();
    return;

    hastag.value = jsondata.hastag;
    tags.value = jsondata.tags;
    relevant.value = jsondata.relevant;

    hasdynamic.value = jsondata.hasdynamic;
    if (hasdynamic.value) {
      const dynamicRes = await getDynamic();
      activeTab.value = "dynamics";
      if (dynamicRes.code === 0) {
        dynamicArr.value = dynamicRes.data.jsondata;
      }
    }

    if (jsondata.scenario) {
      activeTab.value = "scenario";
      scenario.value = jsondata.scenario;
    }

    loading.value = false;

    closeToast();
  });
}

//操作相关=================================
function handleClickOperation(action) {

  const { mobileFunc } = action;
  switch (mobileFunc) {
    case "edit":
      toEdit();
      break;
    case "del":
      handleDel();
      break;
    case "audit":
      handelAudit();
      break;

    case "unaudit":
      handelUnaudit();
      break;

    case "bfjl":
      handelBfjl();
      break;

    case "close":
      handleClose();
      break;

    case "submit":
      handleSubmit();
      break;
    case "flowsubmit":
      handleSubmit();
      break;

    case "contract":
      handleGenerateContract();
      break;

    case "newversion":
      handleNewversion();
      break;

    case "renew":
      handleRenewal();
      break;

    // 认款
    case "rk":
      handleRk();
      break;

    case "review":
      handleReview();
      break;

    // 会议预算报销
    case "hyysbx":
      handleHyysbx();
      break;

    // 会议讲者报销
    case "hyjzbx":
      handleHyjzbx();
      break;

    // 纠错
    case "jcmultirow":
      handleErrorCorrection();
      break;

  }
}

// 纠错

const showErrorCorrectionPopup = ref(false)


function handleErrorCorrection() {
  showErrorCorrectionPopup.value = true
}

function afterErrorCorrectionSubmit() {

  showErrorCorrectionPopup.value = false;
  emitter.emit("listUpload");
}


// 会议讲者报销
const showHyjzbxPopup = ref(false);

const hyjzbxApi = ref("");
const hyjzbxSubmitapi = ref("");
const hyjzbxParams = reactive<params>({});
function handleHyjzbx() {

  showHyjzbxPopup.value = true;
  const { idobject, itemid, idtemplate } = props;
  hyjzbxApi.value = `feebill.ysjzbx.do`;
  hyjzbxSubmitapi.value = `feebill.newsave.do`;
  hyjzbxParams['id'] = itemid;
  hyjzbxParams['op'] = 'hyjzbx';
  hyjzbxParams['idtemplate'] = idtemplate;

}

function alterHyjzbxSubmit() {
  showHyjzbxPopup.value = false;
  updateDetail();
}

// 会议预算报销

const showHyysbxPopup = ref(false);

const hyysbxApi = ref("");
const hyysbxSubmitapi = ref("");
const hyysbxParams = reactive<params>({});
function handleHyysbx() {

  showHyysbxPopup.value = true;
  const { idobject, itemid, idtemplate } = props;
  hyysbxApi.value = `feebill.ysjzbx.do`;
  hyysbxSubmitapi.value = `feebill.newsave.do`;
  hyysbxParams['id'] = itemid;
  hyysbxParams['op'] = 'hyysbx';
  hyysbxParams['idtemplate'] = idtemplate;

}

function afterHyysbxSubmit() {
  showHyysbxPopup.value = false;
  updateDetail();
}


//点评

const showReviewPopup = ref(false);

const reviewContent = ref("");

function handleReview() {
  showReviewPopup.value = true;
}

function handleReviewSubmit() {

  const { idobject } = props;

  let _ybbh = ''
  let _zbbh = ''
  let _rbbh = ''
  let _campaignid = ''
  let _activityid = ''
  let _pxjlbid = ''
  let _yzlh2id = ''
  if (idobject === 'dailyreports') {
    _rbbh = route.query.itemid as string
  } else if (idobject === 'weekreports') {
    _zbbh = route.query.itemid as string
  } else if (idobject === 'monthreport1') {
    _ybbh = route.query.itemid as string
  } else if (idobject === 'campaign') {
    _campaignid = route.query.itemid as string
  } else if (['activity', 'activitybiz', 'activitycust'].includes(idobject as string)) {
    _activityid = route.query.itemid as string
  } else if (idobject === 'pxjlb') {
    _pxjlbid = route.query.itemid as string
  } else if (idobject === 'yzlh2') {
    _yzlh2id = route.query.itemid as string
  }

  let data = {
    dpsj: currenttime(),
    dpnr: reviewContent.value,
    ybbh: _ybbh,
    zbbh: _zbbh,
    rbbh: _rbbh,
    campaignid: _campaignid,
    activityid: _activityid,
    pxjlbid: _pxjlbid,
    yzlh2id: _yzlh2id
  }

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  const url = "dp.newsave.do"
  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      showToast("提交成功");
      showReviewPopup.value = false;
      // setTimeout(() => {
      //   updateDetail();
      // }, 1000);
    }
  }).finally(() => {
    reviewContent.value = ""
  });
}
function currenttime() {
  let d = new Date()
  let year = d.getFullYear()
  let month = d.getMonth() + 1
  let day = d.getDate()
  let hour = d.getHours()
  let minute = d.getMinutes()
  let second = d.getSeconds()
  let time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  return time
}






//认款

const showRkPopup = ref(false);

const rkApi = ref("");
const rkSubmitapi = ref("");
const rkParams = reactive<params>({});
function handleRk() {
  showRkPopup.value = true;
  const { idobject, itemid } = props;
  rkApi.value = `skd.rk.do`;
  rkSubmitapi.value = `${idobject}.newsave.do`;
  rkParams[`skdt_id`] = itemid;
}

function alterRkSubmit() {
  showRkPopup.value = false;
  updateDetail();
}



//检查是否已经审核
function checkIsAudit() {
  return !operation.value.some(item => item.title === '审核')
}

//变更
const showChangePopup = ref(false);

const changeApi = ref("");
const chnageSubmitapi = ref("");
const changeParams = reactive<params>({});
function handleNewversion() {
  if (!checkIsAudit()) {
    showToast("请审核后再做后续操作!")
    return
  }
  showChangePopup.value = true;
  const { idobject, itemid } = props;
  changeApi.value = `${idobject}.newversion.do`;
  // chnageSubmitapi.value = `${idobject}.changesave.do`;
  chnageSubmitapi.value = `${idobject}.newsave.do`;
  changeParams[`${idobject}_id`] = itemid;

}
function alterChangeSubmit() {
  showChangePopup.value = false;
  updateDetail();
}

//续签
const showRenewPopup = ref(false);

const renewApi = ref("");
const renewSubmitapi = ref("");
const renewParams = reactive<params>({});
function handleRenewal() {

  if (!checkIsAudit()) {
    showToast("请审核后再做后续操作!")
    return
  }
  showRenewPopup.value = true;
  const { idobject, itemid } = props;
  renewApi.value = `${idobject}.renew.do`;
  // renewSubmitapi.value = `${idobject}.changesave.do`;
  renewSubmitapi.value = `${idobject}.newsave.do`;

  renewParams[`${idobject}_id`] = itemid;

}
function alterRenewSubmit() {
  showRenewPopup.value = false;
  updateDetail();
}

//编辑
const showEditPopup = ref(false);
const editApi = ref("");
const editSubmitapi = ref("");
const editParams = reactive<params>({});
function toEdit() {
  showEditPopup.value = true;
  const { idobject, itemid } = props;
  editApi.value = `${idobject}.edit.do`;
  editSubmitapi.value = `${idobject}.editsave.do`;
  editParams[`${idobject}_id`] = itemid;
}
function afterEditSubmit() {
  showEditPopup.value = false;
  updateDetail();
}

//提交
function handleSubmit() {
  const { itemid, idobject } = props;
  const realObj = idobject;
  const realId = itemid;
  const data = { [realObj + "_id"]: realId };
  const url = realObj + ".flowsubmit.do";

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      showToast("提交成功");
      setTimeout(() => {
        updateDetail();
      }, 1000);
    }
  });
}

//生成合同
function handleGenerateContract() {
  const { itemid, idobject } = props;
  const realObj = idobject;
  const realId = itemid;
  const data = { ui_tokey: realId };
  const url = realObj + ".savecontract.do";

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      showToast("合同已生成");
      setTimeout(() => {
        updateDetail();
      }, 1000);
    }

  });
}

//删除
function handleDel() {
  const { itemid, idobject } = props;
  showConfirmDialog({
    title: "标题",
    message: "确认要删除当前数据吗?",
  }).then(() => {
    const realObj = idobject;
    const realId = itemid;
    const data = { [realObj + "_id"]: realId };
    const url = realObj + ".del.do";

    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
      duration: 0,
    });
    apiConfigurable(url, data).then((res) => {
      if (res.code === 0) {
        showToast("删除成功");
        routerStore.mode = "reload";
        setTimeout(() => {
          router.go(-1);
        }, 1000);
      }

    });
  });
}
//审核
function handelAudit() {
  const { itemid, idobject } = props;
  const realObj = idobject;
  const realId = itemid;
  const data = { [realObj + "_id"]: realId };
  const url = realObj + ".audit.do";

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      if (res.message) {
        showToast(res.message);
      } else {
        showToast("审核成功");
      }
      setTimeout(() => {
        updateDetail();
      }, 1000);
    }
  });
}
//弃审
function handelUnaudit() {
  const { itemid, idobject } = props;
  const realObj = idobject;
  const realId = itemid;
  const data = { [realObj + "_id"]: realId };
  const url = realObj + ".unaudit.do";

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(url, data).then((res) => {
    if (res.code === 0) {
      showToast("弃审成功");
      setTimeout(() => {
        updateDetail();
      }, 1000);
    }
  });
}
//关闭


const showClosePopup = ref(false);
const closeApi = ref("");
const closeSubmitapi = ref("");
const closeParams = reactive<params>({});
const closeFieldArr = ref([])

function handleClose() {

  const { idobject, itemid } = props;
  closeApi.value = `${idobject}.close.do`;
  closeParams[`${idobject}_id`] = itemid;

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(closeApi.value, closeParams).then(async (res) => {
    if (res.code === 0) {
      if (res.data.jsondata?.length > 0 && res.data.jsondata[0]) {
        closeFieldArr.value = res.data.jsondata[0]?.groupvalue
        showClosePopup.value = true;
      }
    }

  }).finally(() => {
    closeToast();
  });

}

function handleCloseChange(item, value) {
  item.value = value
}
interface submitData {
  [name: string]: any;
}
function handleCloseSubmit() {
  const { idobject, idtemplate } = props;
  closeSubmitapi.value = `${idobject}.closesave.do`;
  showClosePopup.value = false;
  const data: submitData = {};
  data[idobject + "_id"] = route.query.itemid;
  data[idobject + "_idtemplate"] = idtemplate;

  for (let i = 0; i < closeFieldArr.value.length; i++) {
    let itemdata = closeFieldArr.value[i];
    // if (!checkForm(itemdata)) {
    //   return;
    // }
    if (itemdata.sUIType === "ref") {
      data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
      data[itemdata.idObject + "_" + itemdata.sField + "_ref"] = itemdata.value;
    } else if (itemdata.sUIType === "enum") {
      data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
      data[itemdata.idObject + "_" + itemdata.sField + "_enum"] = itemdata.value;
    } else if (
      itemdata.sUIType === "file" ||
      itemdata.sUIType === "picture"
    ) {
      data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
      data[itemdata.idObject + "_" + itemdata.sField + "_title"] = itemdata.value;
    } else {
      data[itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
    }
  }

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(closeSubmitapi.value, data).then((res) => {
    if (res.code === 0) {
      showSuccessToast("提交成功!");
      updateDetail();
    }

  }).finally(() => {
    closeToast();
  });




}

//拜访记录
const showBfjlPopup = ref(false);

const bfjlLoadApi = ref("");
const bfjlLoadParams = reactive({});
const bfjlSubmitApi = ref("");
function handelBfjl() {
  const { idobject, itemid } = props;
  showBfjlPopup.value = true;

  bfjlLoadApi.value = `${idobject}.bfjl.do`;
  bfjlSubmitApi.value = `${idobject}.editsave.do`;
  bfjlLoadParams[`${idobject}_id`] = itemid;
}

function handleBfjlSubmit() {
  showBfjlPopup.value = false;
}



</script>

<style scoped></style>